package parser;

import change.Revision;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.html.DomNode;
import commonutils.MyCollectionUtils;
import commonutils.MyXPathUtils;
import page.Lang;
import pageblock.PageBlock;
import pageblock.PageBlockType;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Evgeniy Krasko
 * Date: 30.10.11
 * Time: 18:01
 */
public class WikiPageParserImpl implements WikiPageParser {
    public static final String INFOBOX_XPATH = "/descendant::TABLE[contains(@class, 'infobox')][1]";
    public static final Map<Lang, String> FIRST_PARAGRAPH_XPATH = new HashMap<Lang, String>();

    static {
        FIRST_PARAGRAPH_XPATH.put(Lang.RU, "/descendant::DIV[contains(@class, 'mw-content-ltr')]/P[contains(string(.),'—')][1]");
        FIRST_PARAGRAPH_XPATH.put(Lang.EN, "/descendant::DIV[contains(@class, 'mw-content-ltr')]/P[contains(string(.),' is ')][1]");
    }


    public List<PageBlock> parse(SgmlPage sourcePage, Revision revision) {
        PageBlock infoBox = this.getInfoBox(sourcePage, revision);
        PageBlock firstParagraph = this.getFirstParagraph(sourcePage, revision);
        return MyCollectionUtils.asListWithoutNulls(infoBox, firstParagraph);
    }


    private PageBlock getFirstParagraph(SgmlPage rawPage, Revision revision) {
        DomNode domNode = MyXPathUtils.getSingleDomNode(rawPage, FIRST_PARAGRAPH_XPATH.get(revision.getWikiPage().getLang()));
        if (domNode == null) {
            return null;
        }
        return new PageBlock(PageBlockType.FIRST_PARAGRAPH, revision, domNode.asText().hashCode());
    }

    private PageBlock getInfoBox(SgmlPage rawPage, Revision revision) {
        DomNode domNode = MyXPathUtils.getSingleDomNode(rawPage, INFOBOX_XPATH);
        if (domNode == null) {
            return null;
        }
        return new PageBlock(PageBlockType.INFO_BOX, revision, domNode.asText().hashCode());
    }


}
